<template>
  <div class="settings_content">
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <!-- 面包屑路径导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item to="/">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row>
        <el-col :span="12">
          <el-form label-width="80px">
            <el-form-item label="编号">
              {{ user.id }}
            </el-form-item>
            <el-form-item label="联系">
              {{ user.mobile }}
            </el-form-item>
            <el-form-item label="名称">
              <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="介绍">
              <el-input type="textarea" v-model="user.intro"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="user.email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="updateProfileLoding"
                @click="onUpdateUser(false)"
              >
                保存设置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :offset="6" :span="4" class="phone_setting">
          <label for="file">
            <el-avatar :size="160" :src="user.photo" @error="errorHandler">
              <img
                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
              />
            </el-avatar>
          </label>
          <h4 @click="$refs.file.click()">点击修改头像</h4>
          <input
            type="file"
            id="file"
            hidden
            @change="onFileChange"
            ref="file"
          />
          <!-- (ref)或者使用label中for与id -->
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      append-to-body
      @closed="onDialogClosed"
      @opened="onDialoOpened"
    >
      <div class="preview_image_wrap">
        <img class="preview_image" :src="previewImage" ref="preview-image" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="updatePhotoLoading"
          @click="onUpdataPhoto"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, updateUserPhoto, updateUserProfile } from "@/api/user";
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import Bus from "@/utils/bus";
export default {
  name: "SettingsIndex",
  components: {},
  data() {
    return {
      user: {
        // 用户资料
        email: "",
        id: null,
        intro: "",
        mobile: "",
        name: "",
        photo: "",
      },
      dialogVisible: false, // 控制预览显示状态
      previewImage: "", // 预览图片
      cropper: null, // 裁剪器示例
      updatePhotoLoading: false, // 更新用户头像 loading 状态
      updateProfileLoding: false, // 更新基本信息的 loading 状态
    };
  },
  created() {
    this.loadUser();
  },
  methods: {
    errorHandler() {
      return true;
    },
    loadUser() {
      getUserProfile().then((res) => {
        this.user = res.data.data;
      });
    },
    onFileChange() {
      // 处于图片预览
      const file = this.$refs.file;
      const blobData = window.URL.createObjectURL(file.files[0]);
      this.previewImage = blobData;
      // 展示弹出层，预览用户选择的图片
      this.dialogVisible = true;

      // 解决选择相同文件不触发
      this.$refs.file.value = "";
    },
    onDialoOpened() {
      // 图片裁切器必须基于 img 进行初始化
      // 注意：img 必须是可见状态才能正常完成初始化
      //       因为我们这里要在对话框里面初始化裁切器
      //       所以务必要在对话框完全打开的状态去进行初始化。
      // 获取图片 DOM 节点
      const image = this.$refs["preview-image"];
      // 初始化裁切器
      this.cropper = new Cropper(image, {
        aspectRatio: 1,
      });
    },
    onDialogClosed() {
      // 关闭对话框销毁裁切器
      this.cropper.destroy();
    },
    onUpdataPhoto() {
      // 让确定按钮开始 loading
      this.updatePhotoLoading = true;
      // 获取图片对象
      this.cropper.getCroppedCanvas().toBlob((file) => {
        const fd = new FormData();
        fd.append("photo", file);
        // 请求提交id
        updateUserPhoto(fd).then((res) => {
          // 关闭对话框
          this.dialogVisible = false;
          this.$message({
            type: "success",
            message: "头像已更新",
          });
          // 更新视图展示
          // 直接把裁切结果的文件对象转为 blob 数据本地预览
          this.updatePhotoLoading = false;
          this.user.photo = window.URL.createObjectURL(file);
        });
      });
    },
    onUpdateUser() {
      // 表单验证
      // 验证通过，提交表单

      // 开启 loading 状态
      const { name, intro, email } = this.user;
      if (name.length < 1 || name.length > 7) {
        this.$message({
          type: "error",
          message: "用户名1~7个字符",
        });
        return;
      }
      // 关闭 loading 状态
      this.updateProfileLoding = true;
      updateUserProfile({ name, intro, email }).then((res) => {
        this.$message({
          type: "success",
          message: "资料已更新",
        });
        this.updateProfileLoding = false;
        // 更新头部当前登录用户的信息
        // 发布通知，用户信息已修改
        Bus.$emit("update-user", this.user);
      });
    },
  },
};
</script>

<style scoped lang="less">
.phone_setting {
  margin-top: 50px;
  h4 {
    letter-spacing: 2px;
    text-indent: 5px;
    margin: 30px 0 0 12px;
  }
}
.preview_image_wrap {
  .preview_image {
    display: block;
    max-width: 100%;
  }
}
</style>
